<script setup lang="ts">
import {
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
  reqHasTrademark,
} from '@/apis/product/trademark'
import type { TradeMark, trademarkArr } from '@/types/trademark'
import { ElMessage, type FormInstance, type UploadProps } from 'element-plus'
import { onMounted, ref } from 'vue'

// 当前页码
const pageNo = ref(1)
// 每页展示多少数据
const limit = ref(3)
//分页总数据
const total = ref(10)
//品牌数据
const trademarkList = ref<trademarkArr>([])
//获取已有品牌数据
const getHasTrademark = async (page = 1) => {
  pageNo.value = page
  const res = await reqHasTrademark(pageNo.value, limit.value)
  if (res.code == 200) {
    trademarkList.value = res.data.records
    total.value = res.data.total
  }
}
// 组件挂载调用
onMounted(() => {
  getHasTrademark()
})
//下拉菜单刷新触发
const handleSizeChange = () => {
  //页码重置
  pageNo.value = 1
  //重新获取数据
  getHasTrademark()
}
// 控制弹框组件是否显示
const dialogVisible = ref(false)
//收集弹框组件数据
const trademarkParmas = ref<TradeMark>({
  tmName: '',
  logoUrl: '',
})
// 获取表单实例
const formRef = ref<FormInstance>()
//自定义规则
const validatorTmName = (_rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称位数大于等于两位'))
  }
}
const validatorLogoUrl = (_rule: any, value: any, callBack: any) => {
  //如果图片上传
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}
//表单校验规则
const rules = {
  tmName: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      validator: validatorLogoUrl,
    },
  ],
}
// 添加品牌
const addTrademark = () => {
  dialogVisible.value = true
  //数据清空
  trademarkParmas.value.id = 0
  trademarkParmas.value.tmName = ''
  trademarkParmas.value.logoUrl = ''
  //清空校验
  formRef.value?.resetFields()
}
//修改品牌
const updateTrademark = (row: TradeMark) => {
  //清空校验
  formRef.value?.resetFields()
  //打开弹框
  dialogVisible.value = true
  //回显数据
  Object.assign(trademarkParmas.value, row)
  //收集id
}
// 删除品牌
const onConfirm = async (id: number) => {
  const res = await reqDeleteTrademark(id)
  if (res.code === 200) {
    // 成功提示
    ElMessage.success('删除品牌成功')
    //重新获取数据
    getHasTrademark(
      trademarkList.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElMessage.error('删除品牌失败')
  }
}
//对话框取消按钮
const cancel = () => {
  dialogVisible.value = false
}
//对话框确认按钮
const confirm = async () => {
  await formRef.value?.validate()
  const res = await reqAddOrUpdateTrademark(trademarkParmas.value)
  if (res.code === 200) {
    // 关闭弹框组件
    dialogVisible.value = false
    // 弹出成功提示
    ElMessage.success(
      trademarkParmas.value.id ? '修改品牌成功' : '添加品牌成功',
    )
    // 重新获取数据
    getHasTrademark(trademarkParmas.value.id ? pageNo.value : 1)
  } else {
    ElMessage.error(trademarkParmas.value.id ? '修改品牌失败' : '添加品牌失败')
    dialogVisible.value = false
  }
}
// 文件上传处理之前事件
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('图片类型必须png、jpg、gif类型')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('上传文件的大小不能超过4MB')
    return false
  }
  return true
}
// 文件上传成功后处理事件
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  // 收集图片的地址
  trademarkParmas.value.logoUrl = response.data
  //清除校验规则
  formRef.value?.clearValidate('logoUrl')
}
</script>

<template>
  <el-card>
    <!-- 按钮组件 -->
    <el-button
      type="primary"
      icon="Plus"
      @click="addTrademark"
      v-has="`btn.Trademark.add`"
    >
      添加品牌
    </el-button>
    <!-- 表格组件 -->
    <el-table
      :data="trademarkList"
      :border="true"
      style="width: 100%; margin: 10px 0px"
    >
      <el-table-column type="index" align="center" label="序号" width="80" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <template #default="{ row }">
          <img
            :src="row.logoUrl"
            style="width: 100px; height: 100px"
            alt="没有图片"
          />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #default="{ row }">
          <el-button
            type="primary"
            icon="Edit"
            circle
            @click="updateTrademark(row)"
          />
          <el-popconfirm
            :title="`你确认删除${row.tmName}吗`"
            icon="Delete"
            @confirm="onConfirm(row.id)"
            width="250px"
          >
            <template #reference>
              <el-button type="primary" icon="Delete" circle />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      :page-sizes="[3, 5, 7, 9]"
      :background="true"
      layout="prev, pager, next,jumper,->,sizes,total,  "
      :total="total"
      @size-change="handleSizeChange"
      @current-change="getHasTrademark"
    />
  </el-card>
  <!-- 弹框组件 -->
  <el-dialog
    v-model="dialogVisible"
    :title="trademarkParmas.id ? '修改品牌' : '添加品牌'"
    width="500"
  >
    <!-- 弹框主题内容 -->
    <el-form
      style="width: 80%"
      :model="trademarkParmas"
      :rules="rules"
      ref="formRef"
    >
      <!-- 输入框 -->
      <el-form-item label="品牌名称" prop="tmName" label-width="100px">
        <el-input
          v-model="trademarkParmas.tmName"
          placeholder="请输入品牌名称"
        ></el-input>
      </el-form-item>
      <!-- 上传图片 -->
      <el-form-item label="品牌LOGO" prop="logoUrl" label-width="100px">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkParmas.logoUrl"
            :src="trademarkParmas.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 底部按钮 -->
    <template #footer>
      <el-button type="primary" @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确认</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
